<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class HTML_Tabla {

    const AGRUPAR_FILAS = 1;
    const NUEVO_PARRAFO = 2;

    var $dataSet; //conjunto de datos (array) a mostrar
    var $columNames; //nombre de las columnas a mostrar
    var $displayColumnNames; //nombre de las columnas a mostrar
    var $breakType; //Puede agruparse filas o roturas tipo informe;
    var $breakPoints; // atributos por los que agrupar la informacion;
    var $construida = false; //si la tabla esta construida o no;
    var $tabla;
    var $resultado;
    var $enlaces;
    var $identidad;

    function HTML_Tabla($set) {       
        $this->dataSet = $set;
        $this->breakType = self::NUEVO_PARRAFO;
        $this->breakPoints = Array();
        $this->enlaces = Array();
    }

    function initColumnNames() {
        //print_r($this->dataSet); 
        foreach ($this->dataSet[0] as $columna => $valor) {
            $this->columnNames[$columna] = $columna;
            $this->displayColumnNames[$columna] = $columna;
        }
    }

    function setEnlaces($identidad, $links) {
        $this->identidad = $identidad;
        $this->enlaces = $links;
    }

    function setDisplayColumnNames($cols) {
        $this->displayColumnNames = $cols;
    }

    function setCabecera($columnas) {
        $this->resultado[] = "<tr>";
        foreach ($columnas as $col => $display) {
            $this->resultado[] = "<th>" . $display . "</th>";
        }
        $this->resultado[] = "</tr>";
    }

    function setBreakPoints($bp) {
        $this->breakPoints = $bp;
    }

    function construct() {
        if (!isset($this->displayColumnNames)) {
            print "usando las columnas por defecto";
            $this->initColumnNames();
            //print_r($this->columnNames);
        }

        $i = 0;
        foreach ($this->dataSet as $fila) {
            foreach ($fila as $col => $display) {
                $this->tabla[$i][$col] = $fila[$col];
                //print_r($this->tabla);
            }
            $i++;
        }

        $this->resultado[] = "<table border=1>";

        $cabecera = '';

        if ($this->breakType == self::AGRUPAR_FILAS) {
            $this->setCabecera($this->columnNames);
        } else {
            $niveles = count($this->breakPoints);  //numero de niveles de ruptura
            $nivel = 0; //empezamos en el nivel mas bajo
            $bpvals = array(); //inicializacion de los valores de ruptura de cada nivel. Se inicializan a la cadena "@ruptura@";
            foreach ($this->breakPoints as $bp) {
                $bpvals[$bp] = "@ruptura@";
            }
            $columnasAMostrar = $this->displayColumnNames;

            if ($niveles == 0) {
                $this->setCabecera($this->displayColumnNames);
            }

            if (sizeof($this->tabla) != 0) {
                //Empezamos a recorrer los datos
                foreach ($this->tabla as $fila) {

                    //comprobar si hay alguna ruptura por orden
                    $i = 0;
                    //print_r($this->breakPoints);
                    for ($i = 0; $i < count($this->breakPoints); $i++) {
                        $camporuptura = $this->breakPoints[$i];
//print_r($fila);
                        if ($fila[$camporuptura] != $bpvals[$camporuptura]) {
                            //hay una ruptura en este campo.
                            //print "dataset[" . $camporuptura . "] (". $fila[$camporuptura] .") != anterior[" . $camporuptura . "] (". $bpvals[$camporuptura] . ")<br>";
                            //Inicializar los puntos de ruptura de este nivel y siguientes
                            $bpvals[$camporuptura] = $fila[$camporuptura];
                            for ($j = $i + 1; $j < $niveles; $j++) {
                                $n = $this->breakPoints[$j];
                                $bpvals[$j] = $fila[$n];
                            }
                            //Escribir la cabecera
                            $colspan = count($this->displayColumnNames) + $niveles;
                            $this->resultado[] = "<tr class='nivel" . $i . "'><th colspan=" . $colspan . " align=left>" . $fila[$camporuptura] . "</th></tr>";
                            unset($columnasAMostrar[$camporuptura]);
                            //Si es el ultimo nivel escribir la cabecera de las lineas

                            if ($i + 1 == $niveles) {
                                $this->resultado[] = "<tr class='cabecera'>";
                                for ($k = 0; $k < $i + 1; $k++) {
                                    $this->resultado[] = "<th>" . "</th>";
                                }
                                foreach ($columnasAMostrar as $col => $display) {
                                    $this->resultado[] = "<th>" . $display . "</th>";
                                }
                                $this->resultado[] = "</tr>";
                            }
                        }
                    }



                    $this->resultado[] = "<tr class='linea'>";

                    for ($k = 0; $k < $i; $k++) {
                        $this->resultado[] = "<td>" . "</td>";
                    }
                    foreach ($columnasAMostrar as $col => $display) {
                        $this->resultado[] = "<td>" . $fila[$col] . "</td>";
                    }

                    foreach ($this->enlaces as $titulo => $link) {
                        $idkey = $this->identidad;
                        $idvalue = $fila[$idkey];
                        if (strrpos($link, "?"))
                                $cad = "&";
                        else   
                            $cad="?";
                        $this->resultado[] = "<td><a href=" . $link . $cad . $idkey . "=" . $idvalue . ">" . $titulo . "</a></td>";
                    }

                    $this->resultado[] = "</tr>";
                }
            }
        }



        $this->resultado[] = "</table>";
    }

    function toHTML() {
        if (!$this->construida)
            $this->construct();

        return $this->resultado;
    }

    function printHTML() {
        foreach ($this->resultado as $linea) {
            print $linea . "\n";
        }
    }

}

class HTML_Form {

    var $nombre;
    var $objeto;
    var $action;
    var $valores = array();
    var $campos = array();
    var $ModeloDatos = array();
    var $estado=array();
    var $html;

    function HTML_Form($nombre, $objeto, $action) {
        $this->nombre = $nombre;
        $this->objeto = $objeto;
        $this->action = $action;
    }

    function setEstado($status){
       $this->estado = $status;    
    }
    
    function setModeloDatos($infoTablas) {
        $this->ModeloDatos = $infoTablas;
    }

    function setValores($arrayValores) {
        $this->valores = $arrayValores;
    }

    function setCampos() {
        $this->campos = getAttributeNames("select * from " . $this->objeto);
    }

    function toHTMLTable() {
        $this->html = array();
//function HTMLFormTablaAction($objeto, $tabla, $action, $arrayvalores = null) {
        $this->html[] = "<table><tr><th colspan=2>" . $this->objeto . "</th></tr>";
        //$atributos = getAttributeNames("select * from " . $objeto)
        $this->setCampos();

        //print_r($atributos);

        $this->html[] = "<form name='add" . $this->objeto . "Form' action='" . $this->action . "' method='post' id='add" . $this->objeto . "Form'>";
        $this->html[] = "<input type='hidden' name='nombreObjeto' value='" . $this->objeto . "'>";

        //print_r($arrayvalores);
        foreach ($this->valores as $key => $val) {
            $this->html[] = "<input type='hidden' name='" . $key . "' value='" . $val . "'>";
        }


        foreach ($this->campos as $at) {
            $atname = $at['name'];
            if ((array_key_exists($atname, $this->valores)) && (isset($this->valores[$atname])))
                continue;

            if ($this->ModeloDatos[$this->objeto][$atname]['tipo'] == 'key') {
                continue;
            }

            $this->html[] = "<tr>";
            if ($this->ModeloDatos[$this->objeto][$atname]['tipo'] == 'hidden') {
                $str = '';
            } else {
                $str = $atname;
            }



            $this->html[] = "<td>" . $str . "</td>";

            if (isset($this->ModeloDatos[$this->objeto][$atname]['fkinfo'])) {
                if ($this->ModeloDatos[$this->objeto][$atname]['edit'] === 'select') {
                    //print_r($obj);
                    //print($obj[0][$nombreCampo]);
                    $sel = new HTML_Select($atname, null);
                    $sel->setModeloDatos($this->ModeloDatos);
                    $sel->setFKInfo($this->ModeloDatos[$this->objeto][$atname]['fkinfo']['tablaR'], $this->ModeloDatos[$this->objeto][$atname]['fkinfo']['campoR'], $this->ModeloDatos[$this->objeto][$atname]['fkinfo']['campoShow']);
                    $sel->setEstado($this->estado);
                    $sel->printHTML($sel->toHTML());
                    $str = $sel->toHTML();
                    //$str = getSelectHTML($this->ModeloDatos[$this->objeto][$atname]['fkinfo']['tablaR'], $this->ModeloDatos[$this->objeto][$atname]['fkinfo']['campoR'], $this->ModeloDatos[$this->objeto][$atname]['fkinfo']['campoShow'], $atname, null);
                } else if ($this->ModeloDatos[$this->objeto][$atname]['edit'] === 'search') {
                    $str = "<input type='text' size=5 name='" . $atname . "' value=''/ onchange='alert(\"hola\")'>" .
                            "<input type='button' value='...' onclick='popup(\"search" . $tabla[$atname]['fkinfo']['tablaR'] . ".php\");'>" .
                            "<input type=text size=50 name='descripcion' readonly=true>";
                    //"<input type='button' value='...' onclick='alert(\"hola\");'/>";
                }
            } else {
                $str = "<input type='" . $this->ModeloDatos[$this->objeto][$atname]['tipo'] . "' name='" . $atname . "' value=''/>";
            }

            $this->html[] = "<td>" . $str . "</td>";
            $this->html[] = "</tr>";
        }

        $this->html[] = "<tr><td colspan=2>" . "<input type='submit' value='Aceptar'>" . "<td></tr>";
        $this->html[] = "</form>";
        $this->html[] = "</table>";
    }

    function printHTML(){
        foreach ($this->html as $linea){
            print $linea;
        }
    }
}

class HTML_Select {

    var $estado; //Almacena informacion relevanre sobre el estado de la sesion para obtener correcatmente el select
    var $campo = array();
    var $FKInfo = array();
    var $ModeloDatos = array();
    var $html = array();

    function HTML_Select($nombreCampo, $valorCampo) {
        $this->campo['nombre'] = $nombreCampo;
        $this->campo['valor'] = $valorCampo;
    }

    function setModeloDatos($infoTablas) {
        $this->ModeloDatos = $infoTablas;
    }

    function setEstado($status) {
        $this->estado = $status;
    }

    function printHTML() {
        
    }

    function setFKInfo($FKLookupTable, $FKLookupField, $FKShowField) {
        $this->FKInfo['lookuptable'] = $FKLookupTable;
        $this->FKInfo['lookupfield'] = $FKLookupField;
        $this->FKInfo['showfield'] = $FKShowField;
    }

    function toHTML() {

        $sql = "select * from " . $this->FKInfo['lookuptable'];
        $filtro = " where 1=1";
        //print_r($this);
        if (isset($this->ModeloDatos['fkinfo'][$this->FKInfo['lookuptable']])) {
            $fkfield= $this->ModeloDatos['fkinfo'][$this->FKInfo['lookuptable']]['lkField'];            
            $lfield = $this->ModeloDatos['fkinfo'][$this->FKInfo['lookuptable']]['fkField'];           
            
            //print_r($this->ModeloDatos['fkinfo'][$this->FKInfo['lookuptable']]['fkTable']);
            //print_r($this->estado);
            
            $fkvalue = $this->estado[$this->ModeloDatos['fkinfo'][$this->FKInfo['lookuptable']]['fkTable']][0][$lfield];
            $filtro .= " and " . $fkfield . "=" . $fkvalue;
        }

        $sql .= $filtro;

        //print $sql;
        $datos = select2($sql);
        //print_r($datos);
        $str = "<select name='" . $this->campo['nombre'] . "'>";

        foreach ($datos as $fila) {

            $selected = "";
            if ($fila[$this->FKInfo['lookupfield']] == $this->campo['valor']) {
                $selected = "selected";
            }
            //    print_r($fila);
            $str .= "<option value='" . $fila[$this->FKInfo['lookupfield']] . "' " . $selected . ">" . $fila[$this->FKInfo['showfield']] . "</option>";
        }
        $str.="</select>";
        //print $str;

        return $str;
    }

}

?>
